package myJs.user

import myJs.Implicits._
import myJs.Utils._
import scala.scalajs.js.Dynamic.{global=>g}
import myJs.myPkg.LayerOptions
import myJs.myPkg.bootstrap.Bootstrap.default._
import myJs.myPkg.jquery._
import myJs.tool.Tool
import myJs.tool.Tool._
import org.scalajs.dom.{Event, _}
import org.scalajs.dom.ext.Ajax
import scalatags.Text.all.s
import shared.VarTool

import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import scala.scalajs.js
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import scalatags.Text.all._

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("UserProfile")
object UserProfile {

  val modalId = "modal"

  @JSExport("init")
  def init = {
    bootStrapValidator
    refreshPersonInfo

  }

  @JSExport("myRun")
  def myRun = {
    val bv = $("#form").bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val formData = new FormData(document.getElementById("form").toHTMLFormElement)
      $(":disabled").attr("disabled", false)
      val element = div(id := "content",
        span(id := "info", messages("running"),
          span(id := "progress", "。。。")), " ",
        img(src := "/assets/images/running2.gif", cls := "runningImage", width := 30, height := 20)
      ).render
      val layerOptions = LayerOptions.title(Tool.zhInfo).closeBtn(0).skin("layui-layer-molv").btn(js.Array())
      val index = layer.alert(element, layerOptions)
      val url = g.jsRoutes.controllers.UserController.updateImage().url.toString
      val xhr = new XMLHttpRequest
      xhr.open("post", url)
      xhr.upload.onprogress = progressHandlingFunction
      xhr.onreadystatechange = (e) => {
        if (xhr.readyState == XMLHttpRequest.DONE) {
          val data = xhr.response
          layer.close(index)
          val imageUrl = g.jsRoutes.controllers.UserController.getAvatarImage().url.toString
          $(".avatarImage").attr("src", s"${imageUrl}?random=${new js.Date()}")
          $(s"#${modalId}").modal("hide")
        }
      }
      xhr.send(formData)
    }
  }

  @JSExport("imageUpdateModalShow")
  def imageUpdateModalShow = {
    $(s"#${modalId}").modal("show")
  }

  def refreshPersonInfo = {
    val url = g.jsRoutes.controllers.UserController.getUserById().url.toString
    Ajax.get(url = s"${url.noCache}&id=${getId}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJDJAn.toMyJDS
      rs.foreach { case (k, v) =>
        $(s"#personInfo [id='${k}']").text(v)
      }
      val userId = "MP" + getId.reverse.padTo(8, 0).reverse.mkString
      $(s"#personInfo #userId").text(userId)
    }
  }

  def getId = {
    g.id.toString
  }

  def bootStrapValidator = {
    val maxNumber = Double.MaxValue
    val dict: js.Dictionary[js.Any] = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "file" ->{
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" ->s"${messages("null")}"
              ),
              "file" -> js.Dictionary(
                "message" -> messages("IncorrectFormat"),
                "extension" -> "jpg,jpeg,png",
              ),
            )
          )
        } ,

      )
    )
    $("#form").bootstrapValidator(dict)

  }

}
